from urllib import request, error
import winsound
import time

import conf

servers = [
    {
        'name': '0. 吉珠 wlkc',
        'url': 'http://wlkc.jluzh.com/meol/index.do'
    },
    {
        'name': '1. welearn 外研社英语',
        'url': 'https://welearn.sflep.com/2019/index.aspx'
    }
]


def beep():
    """提示音"""
    winsound.Beep(880, 4000)


def website_status(url) -> int:
    """网络状态"""
    req = request.Request(url=url, method='GET')
    try:
        with request.urlopen(req) as f:
            return f.status
    except error.HTTPError:
        return 500


def choice_server() -> dict:
    """选择服务器"""
    print('选择服务器')
    for server in servers:
        print(server['name'])
    server_idx = int(input('请输入序号：'))
    return servers[server_idx]


def sendMsgBark(msg: str):
    req = request.Request(url=('https://api.day.app/' + conf.barkKey + '/Server_status_changed/' + msg), method='GET')
    try:
        with request.urlopen(req) as f:
            print('Send meesage to user\'s Bark')
            print('Message send status' + str(f.status))
    except Exception:
        print('Send message failed')


def alert():
    beep()
    sendMsgBark('')


if __name__ == "__main__":
    # Choice server
    server = choice_server()
    print(server['name'])

    # Startup info
    print('Playing 4 sec beep, plese check you speaker volume !')
    beep()
    print('Test beep end')
    print('Start up monitoring website')

    # Monitoring
    server_to_mnt = server['url']
    status: int = 200
    while True:
        try:
            tmp_status = website_status(server_to_mnt)
            print(tmp_status)
            if tmp_status != status:
                print('Server status changed !')
                alert()
                status = tmp_status
        except Exception as e:
            print('Request failed, maybe network disconnect')
        time.sleep(10)
